package mashuaiproject.mashuaiproject.controller;

import org.springframework.http.HttpStatus;
import  org.springframework.http.MediaType;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomizeErrorContrller implements ErrorController {

    @Override
    public String getErrorPath() {
        return "error";
    }

    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, Model model){
        HttpStatus status=getStaus(request);
        if(status.is4xxClientError()){
            model.addAttribute("message","q请求有错误");
        }
        if(status.is5xxServerError()){
            model.addAttribute("message","服务器冒烟啦");
        }
        return new ModelAndView("error");
    }

    private HttpStatus getStaus(HttpServletRequest request) {
        Integer stautuCode=(Integer)request.getAttribute("javax.servlet.error.status_code");
        if(stautuCode!=null){
            return  HttpStatus.INTERNAL_SERVER_ERROR;
        }
     try {
         return  HttpStatus.valueOf(stautuCode);
     }catch (Exception ex){
         return HttpStatus.INTERNAL_SERVER_ERROR;
     }
    }
}
